package com.aidex.biz.controller;

import java.awt.datatransfer.StringSelection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.aidex.biz.domain.*;
import com.aidex.biz.domain.enums.CustomerEnum;
import com.aidex.biz.service.*;
import com.aidex.common.annotation.Log;
import com.aidex.common.core.domain.R;
import com.aidex.common.core.redis.RedisCache;
import com.aidex.common.utils.StringUtils;
import com.github.pagehelper.PageInfo;
import com.aidex.common.core.page.PageDomain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.aidex.common.enums.BusinessType;
import com.aidex.common.utils.poi.ExcelUtil;
import javax.validation.constraints.*;
import org.springframework.web.bind.annotation.*;
import com.aidex.common.core.controller.BaseController;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import com.aidex.common.utils.SecurityUtils;

/**
 * 客户进件Controller
 * @author sean
 * @email 2074844820@qq.com
 * @date 2023-12-11
 */
@RestController
@RequestMapping("/biz/bizJinjianInfo")
public class JinjianInfoController extends BaseController
{
    @Autowired
    private JinjianInfoService jinjianInfoService;

    @Autowired
    private ToHomeUserService toHomeUserService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private JinjianBillService jinjianBillService;

    @Autowired
    private CapBillService capBillService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private JinjianCodeService jinjianCodeService;

    @Autowired
    private CustomerDongtaiService customerDongtaiService;

    /**
     * 查询客户进件列表
     */
    @GetMapping("/list")
    public R<PageInfo> list(JinjianInfo jinjianInfo, HttpServletRequest request, HttpServletResponse response)
    {
        if(SecurityUtils.isAdmin(SecurityUtils.getUserId())){
                jinjianInfo.setCompanyId(null);
        }else{
                     jinjianInfo.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
                 }
        jinjianInfo.setPage(new PageDomain(request, response));
        return R.data(jinjianInfoService.findPage(jinjianInfo));
    }

    @GetMapping("/mylist")
    public R<PageInfo> mylist(JinjianInfo jinjianInfo, HttpServletRequest request, HttpServletResponse response)
    {
        jinjianInfo.setUserId(SecurityUtils.getUserId());
        jinjianInfo.setPage(new PageDomain(request, response));
        return R.data(jinjianInfoService.findPage(jinjianInfo));
    }

    /**
     * 获取客户进件详细信息
     */
    @GetMapping(value = "/{id}")
    public R<JinjianInfo> detail(@PathVariable("id") String id)
    {
        return R.data(jinjianInfoService.get(id));
    }

    /**
     * 新增客户进件
     */
    @Log(title = "客户进件", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody @Validated  JinjianInfo jinjianInfo)
    {
        Integer index=jinjianCodeService.findMaxSort(new JinjianCode());
        if(null==index){
            index=1;
        }
        String indeStr="";
        if(index>=10){
            indeStr="000"+index;
        }else{
            indeStr="0000"+index;
        }
        if(index>=100){
            indeStr="000"+index;
        }
        if(index>=1000){
            indeStr="0"+index;
        }
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMDD");
        jinjianInfo.setId("CODE-"+ simpleDateFormat.format(new Date())+indeStr);
        jinjianInfo.setIsNewRecord();
        if(!StringUtils.isEmpty(jinjianInfo.getTuHomeUserId())){
            ToHomeUser toHomeUser=toHomeUserService.get(jinjianInfo.getTuHomeUserId());
            if(null!=toHomeUser){
                toHomeUser.setYushenStatus("1");
                toHomeUser.setJinjianId(jinjianInfo.getId());
                toHomeUserService.save(toHomeUser);
            }

        }
        // 预审申请
        if(!StringUtils.isEmpty(jinjianInfo.getCustomerId())){
            Customer customer=customerService.get(jinjianInfo.getCustomerId());
            if(null!=customer){
                customer.setBusinessStatus(CustomerEnum.CUS_YS.getStatus());
                customer.setAmount(jinjianInfo.getYxEdu().toString());
                customerService.save(customer);
            }
        }



        jinjianInfoService.save(jinjianInfo);

        CustomerDongtai customerDongtai=new CustomerDongtai();
        customerDongtai.setCustomerId(jinjianInfo.getCustomerId());
        customerDongtai.setType("2");
        customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-新增预审进件");
        customerDongtaiService.save(customerDongtai);

        // 保存序号
        JinjianCode jinjianCode=new JinjianCode();
        jinjianCode.setSort(index);
        return R.status(jinjianCodeService.save(jinjianCode));
    }

    /**
     * 修改客户进件
     */
    @Log(title = "客户进件", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@RequestBody @Validated JinjianInfo jinjianInfo)
    {
        if(!StringUtils.isEmpty(jinjianInfo.getStatus())){
            if("1".equals(jinjianInfo.getStatus())){
                Customer customer=customerService.get(jinjianInfo.getCustomerId());
                customer.setBusinessStatus(CustomerEnum.JinJian_SP.getStatus());
                customerService.save(customer);
            }
        }
        if(!StringUtils.isEmpty(jinjianInfo.getJinjianStatus())){
            if("3".equals(jinjianInfo.getJinjianStatus())){
                Customer customer=customerService.get(jinjianInfo.getCustomerId());
                customer.setBusinessStatus(CustomerEnum.CUS_QY.getStatus());
                customerService.save(customer);
            }
            // 签约
            if("8".equals(jinjianInfo.getJinjianStatus())){
                Customer customer=customerService.get(jinjianInfo.getCustomerId());
                customer.setBusinessStatus(CustomerEnum.CHENG_JIAO.getStatus());
                customerService.save(customer);
                // 生成 资方结算/费用管理
                JinjianBill jinjianBill=null;
                jinjianBill=jinjianBillService.getByJinjianId(jinjianInfo.getId());
                if(null==jinjianBill){
                    jinjianBill=new JinjianBill();
                    jinjianBill.setId(UUID.randomUUID().toString());
                    jinjianBill.setIsNewRecord();
                    jinjianBill.setJinjianId(jinjianInfo.getId());
                    jinjianBill.setCusName(jinjianInfo.getCustomerName());
                    jinjianBill.setCustomerId(jinjianInfo.getCustomerId());
                    jinjianBill.setStatus("0");
                    jinjianBill.setSqAmount(jinjianInfo.getYxEdu()); //申请额度
                    jinjianBill.setFkAmount(jinjianInfo.getSjEdu()); // 放款额度
                    jinjianBill.setServiceAmount(jinjianInfo.getServiceAmount()); // 提交收入金额
                    jinjianBill.setServiceName(jinjianInfo.getServcieUserName());
                    jinjianBill.setServiceId(jinjianInfo.getServcieUserId());
                    jinjianBill.setUserId(customer.getUserId());
                    jinjianBill.setUserName(customer.getUserName());
                    jinjianBill.setDeptId(customer.getDeptId());
                    jinjianBill.setQdTime(jinjianInfo.getQiandanTime());
                    jinjianBill.setFkTime(jinjianInfo.getFkTime());
                    jinjianBill.setCaiwuCheck("0");
                    jinjianBill.setIsZuofei("0");
                    jinjianBillService.save(jinjianBill);
                    // 资方结算
                    CapBill capBill=new CapBill();
                    capBill.setJinjianId(jinjianInfo.getId());
                    capBill.setCusName(jinjianInfo.getCustomerName());
                    capBill.setCustomerId(jinjianInfo.getCustomerId());
                    capBill.setSqAmount(jinjianInfo.getYxEdu()); //申请额度
                    capBill.setFkAmount(jinjianInfo.getSjEdu()); // 放款额度
                    capBill.setServiceName(jinjianInfo.getServcieUserName());
                    capBill.setServiceId(jinjianInfo.getServcieUserId());
                    capBill.setUserId(customer.getUserId());
                    capBill.setUserName(customer.getUserName());
                    capBill.setQdTime(jinjianInfo.getQiandanTime());
                    capBill.setFkTime(jinjianInfo.getFkTime());
                    capBill.setStatus("0");
                    capBill.setOrgType(jinjianInfo.getOrgType());
                    capBill.setProductId(jinjianInfo.getProductId());
                    capBill.setProductName(jinjianInfo.getProductName());
                    capBillService.save(capBill);
                }else{
                    // 如果不为空，且是作废状态
                    if("1".equals(jinjianBill.getIsZuofei())){
                        jinjianBill=new JinjianBill();
                        jinjianBill.setId(UUID.randomUUID().toString());
                        jinjianBill.setIsNewRecord();
                        jinjianBill.setJinjianId(jinjianInfo.getId());
                        jinjianBill.setCusName(jinjianInfo.getCustomerName());
                        jinjianBill.setCustomerId(jinjianInfo.getCustomerId());
                        jinjianBill.setStatus("0");
                        jinjianBill.setSqAmount(jinjianInfo.getYxEdu()); //申请额度
                        jinjianBill.setFkAmount(jinjianInfo.getSjEdu()); // 放款额度
                        jinjianBill.setServiceAmount(jinjianInfo.getServiceAmount()); // 提交收入金额
                        jinjianBill.setServiceName(jinjianInfo.getServcieUserName());
                        jinjianBill.setServiceId(jinjianInfo.getServcieUserId());
                        jinjianBill.setUserId(customer.getUserId());
                        jinjianBill.setUserName(customer.getUserName());
                        jinjianBill.setDeptId(customer.getDeptId());
                        jinjianBill.setQdTime(jinjianInfo.getQiandanTime());
                        jinjianBill.setFkTime(jinjianInfo.getFkTime());
                        jinjianBill.setCaiwuCheck("0");
                        jinjianBill.setIsZuofei("0");
                        jinjianBillService.save(jinjianBill);
                    }
                }
            }
        }

        return R.status(jinjianInfoService.save(jinjianInfo));
    }


    /**
     * 删除客户进件
     */
    @Log(title = "客户进件", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable String[] ids)
    {
        return R.status(jinjianInfoService.deleteJinjianInfoByIds(ids));
    }

    /**
     * 获取最大编号
     */
    @GetMapping("/findMaxSort")
    public R findMaxSort()
    {
        return R.data(jinjianInfoService.findMaxSort(new JinjianInfo()));
    }

    /**
     * 导出客户进件列表
     */
    @Log(title = "客户进件", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public R export(JinjianInfo jinjianInfo)
    {

            if(SecurityUtils.isAdmin(SecurityUtils.getUserId())){
                    jinjianInfo.setCompanyId(null);
            }else{
                         jinjianInfo.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
                     }
        List<JinjianInfo> list = jinjianInfoService.findList(jinjianInfo);
        ExcelUtil<JinjianInfo> util = new ExcelUtil<JinjianInfo>(JinjianInfo.class);
        return util.exportExcel(list, "客户进件数据");
    }

}
